<template>
  <div class="enterprise-info-query-container">
    <HeaderIndex title="企业信息查询" ref="headerContainer" />
    <div class="enterprise-info" ref="enterpriseInfo">
      <p>*部分数据来源自天眼查</p>
      <div class="info-title">
        <h2>{{ companyInfo.companyName }}</h2>
        <!--<van-icon name="arrow-up" />-->
        <van-button :icon="expandTheStatus ? 'arrow-down' : 'arrow-up'" plain color="#429df8" @click="expandAndCollapse">
          {{ expandTheStatus ? "收起" : "展开" }}
        </van-button>
      </div>
      <div :class="[expandTheStatus ? 'e-info' : 'e-info-collapse']">
        <div class="e-info-item">
          <div>
            <span>简称：</span><span>{{ dataInfo.alias }}</span>
          </div>
          <div>
            <span>所属行业：</span><span>{{ dataInfo.industry }}</span>
          </div>
        </div>
        <div class="e-info-item">
          <div>
            <span>邮箱：</span
            ><span
              ><a :href="'mailto:' + dataInfo.email">{{ dataInfo.email }}</a></span
            >
          </div>
          <div>
            <span>法定代表人：</span
            ><span @click="handleBusinessRole(dataInfo.legalPersonName)">{{ dataInfo.legalPersonName }}</span>
          </div>
        </div>
        <div class="e-info-item">
          <div>
            <span>网址：</span><span>{{ dataInfo.websiteList }}</span>
          </div>
          <div>
            <span>地址：</span><span>{{ dataInfo.regLocation }}</span>
          </div>
        </div>
      </div>
    </div>
    <ul class="nav-list" ref="navList" @touchmove="slideMove" id="navigationBar-inquire">
      <li
        :class="{ active: item.isActive }"
        v-for="(item, i) in navList"
        :key="i"
        @click="
          handleParentList({
            id: item.id,
            name: item.name,
            type: item.defaultType,
            navRequestStatus: item.navRequestStatus,
          })
        "
      >
        {{ item.name }}
      </li>
    </ul>
    <!--虚拟滚动条-->
    <div class="bg-scrollFake">
      <div class="scrollFake" id="scrollFake-inquire">
        <div class="scrollBar" :style="{ left: slideLeft + 'px' }" id="scrollBar-inquire"></div>
      </div>
    </div>
    <ul class="nav-list-children" ref="navListChildren" v-if="type !== 'PresentContent'">
      <li
        :class="[children.type, children.isActive ? 'active-children' : '']"
        :data-class="children.type"
        v-for="(children, index) in getNavChildren(id)"
        :key="index"
        @click="
          handleChildrenList(
            {
              id,
              index,
              type: children.type,
              name: children.name,
              navRequestStatus: children.navRequestStatus,
            },
            children,
          )
        "
      >
        {{ children.name }}
      </li>
    </ul>
    <EnterpriseDetailsIndex
      ref="enterpriseDetailsContainer"
      :type="type"
      :dataInfo="dataInfo"
      :vantListGather="vantListGather"
      :riskList="riskList"
      :parentCompanyObj="parentCompanyObj"
      :riskTitle="riskTitle"
      @onLoad="onLoad"
    />
  </div>
</template>

<script>
import { elementSlide, Toast, jumpPage } from "@/utils";
import HeaderIndex from "@/components/header";
import EnterpriseDetailsIndex from "@/components/enterpriseDetails";
import {
  getEnterpriseInfo,
  getShareholderInfo,
  getTelecomLicense,
  getCertificate,
  getInvestInfo,
  getBranchInfo,
  getParentCompany,
  getRiskInfo,
  getChangeInfo,
  getBiddingInformation,
} from "@/api";

//企业信息导航数据类型
const ENTERPRISE_INFO_TYPE = {
  shareholderInfo: getShareholderInfo, //股东信息
  manageInfo: getTelecomLicense, //经营信息-电信许可
  credential: getCertificate, //资质证书
  outboundInvestment: getInvestInfo, //对外投资
  branch: getBranchInfo, //分支机构
  changeInfo: getChangeInfo, //变更记录
  biddingInformation: getBiddingInformation, //招投标信息
};

/**
 * NO_REQUESTS -> 没有请求（如：工商、主要人员）
 * SAME_PARAMETERS_REQUEST -> 参数相同的请求（如：股东信息、资质证书、投资情况）
 * RISK_DETAILS_REQUEST -> 风险详情的请求
 * PARENT_COMPANY_REQUEST -> 总公司的请求
 */
const NO_REQUESTS = 0,
  SAME_PARAMETERS_REQUEST = 1,
  RISK_DETAILS_REQUEST = 2,
  PARENT_COMPANY_REQUEST = 3,
  SHORTEST_PATH = 4;
//风险id
const RISK_ID = 3;

export default {
  name: "EnterpriseInfoQuery",
  components: {
    HeaderIndex,
    EnterpriseDetailsIndex,
  },
  data() {
    return {
      expandTheStatus: true, //展开状态
      id: 1, //保存点击的id
      dataInfo: {}, //显示工商和主要人员信息
      type: "businessCircles", //显示的列表类型，根据不同类型请求不同的接口
      navList: [
        //导航列表
        {
          id: 1, //id
          name: "基本信息", //导航名称
          defaultType: "businessCircles", //默认选中子级列表的第一个内容
          isActive: true, //是否选中
          navRequestStatus: NO_REQUESTS, //导航请求的状态
          children: [
            //子级导航列表
            {
              name: "工商信息", //导航名称
              type: "businessCircles", //显示的列表类型
              isActive: true, //是否选中
              navRequestStatus: NO_REQUESTS, //导航请求的状态
            },
            {
              name: "主要人员",
              type: "keyPersonnel",
              isActive: false,
              navRequestStatus: NO_REQUESTS,
            },
            {
              name: "股东信息",
              type: "shareholderInfo",
              isActive: false,
              navRequestStatus: SAME_PARAMETERS_REQUEST,
            },
            {
              name: "变更记录",
              type: "changeInfo",
              isActive: false,
              navRequestStatus: SAME_PARAMETERS_REQUEST,
            },
          ],
        },
        {
          id: 2, //id
          name: "经营信息", //导航名称
          defaultType: "manageInfo", //默认选中子级列表的第一个内容
          isActive: false, //是否选中
          navRequestStatus: SAME_PARAMETERS_REQUEST, //导航请求的状态
          children: [
            //子级导航列表
            {
              name: "经营信息-电信许可",
              type: "manageInfo",
              isActive: false,
              navRequestStatus: SAME_PARAMETERS_REQUEST,
            },
            {
              name: "资质证书",
              type: "credential",
              isActive: false,
              navRequestStatus: SAME_PARAMETERS_REQUEST,
            },
            {
              name: "招投标信息",
              type: "biddingInformation",
              isActive: false,
              navRequestStatus: SAME_PARAMETERS_REQUEST,
            },
          ],
        },
        {
          id: 3,
          name: "投资情况",
          defaultType: "outboundInvestment",
          isActive: false,
          navRequestStatus: SAME_PARAMETERS_REQUEST,
          children: [
            {
              name: "对外投资",
              type: "outboundInvestment",
              isActive: true,
              navRequestStatus: SAME_PARAMETERS_REQUEST,
            },
            {
              name: "分支机构",
              type: "branch",
              isActive: false,
              navRequestStatus: SAME_PARAMETERS_REQUEST,
            },
            {
              name: "总公司",
              type: "parentCompany",
              isActive: false,
              navRequestStatus: PARENT_COMPANY_REQUEST,
            },
          ],
        },
        {
          id: 4,
          name: "风险情况",
          defaultType: "ownRisk",
          isActive: false,
          navRequestStatus: RISK_DETAILS_REQUEST,
          children: [
            {
              name: "自身风险",
              type: "ownRisk",
              isActive: true,
              navRequestStatus: NO_REQUESTS,
            },
            {
              name: "周边风险",
              type: "peripheryRisk",
              isActive: false,
              navRequestStatus: NO_REQUESTS,
            },
            {
              name: "历史风险",
              type: "historicalRisk",
              isActive: false,
              navRequestStatus: NO_REQUESTS,
            },
            {
              name: "预警提示",
              type: "alertPrompt",
              isActive: false,
              navRequestStatus: NO_REQUESTS,
            },
          ],
        },
        {
          id: 5,
          name: "最短路径发现",
          defaultType: "PresentContent",
          isActive: false,
          navRequestStatus: SHORTEST_PATH,
        },
      ],
      vantListGather: {
        //加载数据集合
        list: [], //展示的数据
        pageNum: 1, //页码
        loading: false, //下拉加载状态
        finished: false, //数据是否加载完
        offset: 0, //离页面底部的距离
        finishedText: "数据到底啦~~", //加载完成显示的文字
      },
      parentCompanyObj: {}, //总公司数据
      riskList: [], //风险信息数据
      navListObj: {}, //导航栏状态信息
      riskTitle: "自身风险", //风险信息名称
      companyInfo: this.$route.query,
      slideLeft: 0, //滑块动态left值
      scrollBarWidth: 0, //滑块宽度
      navWidth: 0, //导航栏宽度
      slidingRegionDom: null, //滑动区域dom
      scrollAreaWidth: 0, //滑动区域可见宽度
      actualWidth: 0, //滑块区域实际宽度
    };
  },
  mounted() {
    this.domGain();
    this.getEnterpriseInfoData();

    //如果为true表示返回的上一页，如果为false表示进入新的页面
    if (!JSON.parse(sessionStorage.getItem("isGoBack"))) return;

    const {
      id = 1,
      type = "businessCircles",
      index = 0,
      navRequestStatus = 0,
      name = "基本信息",
    } = JSON.parse(sessionStorage.getItem(this.companyInfo.id)) || {};

    //设置一级导航栏目选中
    this.handleParentList({
      id,
      type,
      index,
      navRequestStatus,
      name,
    });

    //设置二级导航栏目选中展示
    this.setTwoStageNavActive(id, index);

    //设置二级导航栏滑动，让点击的栏目滚动到中间区域
    this.$nextTick(() => {
      elementSlide(this.$refs.navListChildren, `.${type}`);
    });
  },
  methods: {
    expandAndCollapse() {
      this.expandTheStatus = !this.expandTheStatus;
      if (this.type === "PresentContent") {
        //当页面为最短路径时，初始化图表
        this.$refs.enterpriseDetailsContainer.$refs.presentContent.checkRelation();
      }
    },
    slideMove() {
      // 根据滑动区域的滚动位置和实际宽度，计算滑动比例
      const scale = this.slidingRegionDom.scrollLeft / (this.actualWidth - this.scrollAreaWidth);
      // 根据计算得到的滑动比例，调整导航条左侧偏移量，以实现滑动效果
      this.slideLeft = (this.navWidth - this.scrollBarWidth) * scale;
    },
    //DOM获取
    domGain() {
      this.navWidth = document.getElementById("scrollFake-inquire").offsetWidth; //导航栏宽度
      this.scrollBarWidth = document.getElementById("scrollBar-inquire").offsetWidth; //滑块宽度
      this.slidingRegionDom = document.getElementById("navigationBar-inquire"); //滑动区域DOM
      this.scrollAreaWidth = this.slidingRegionDom.offsetWidth; //滑块区域可见宽度
      this.actualWidth = this.slidingRegionDom.scrollWidth; //滑块区域实际宽度
    },
    /**
     * 获取基本信息
     */
    async getEnterpriseInfoData() {
      try {
        Toast.startLoading();

        //获取页面基本信息
        this.dataInfo = await getEnterpriseInfo({
          companyName: this.companyInfo.companyName,
        });
      } finally {
        this.$nextTick(() => {
          this.setEnterpriseDetailsConHeight();
        });

        Toast.closeLoading();
      }
    },

    /**
     * 获取股东信息、电信许可、资质证书、对外投资、分支机构、总公司数据
     * @param {*} type 请求接口的类型
     */
    async getData(type) {
      try {
        Toast.startLoading();

        //加载状态开始
        this.vantListGather.loading = true;
        const data = { value: null };
        //根据不同的类型来请求数据
        if (type !== "biddingInformation") {
          data.value = (await ENTERPRISE_INFO_TYPE[type]({
            companyName: this.companyInfo.companyName,
            pageNum: this.vantListGather.pageNum,
          })) || { items: [] };
        } else {
          data.value = (await ENTERPRISE_INFO_TYPE[type]({
            companyName: this.companyInfo.companyName,
            pageNum: this.vantListGather.pageNum,
            searchType: "",
            type: "",
          })) || { items: [] };
        }
        //将之前的列表数据与加载下一页的数据合并在一起形成新的数据列表进行展示
        this.vantListGather.list = [...this.vantListGather.list, ...data.value.items];
        //数据全部加载完成显示文本
        this.vantListGather.finished ||= this.vantListGather.list.length >= data.value.total;
      } finally {
        //加载状态结束
        this.vantListGather.loading = false;

        Toast.closeLoading();
      }
    },

    /**
     * 获取风险信息数据
     */
    async getRiskInfo() {
      try {
        Toast.startLoading();

        //获取风险数据
        const { riskList = [] } =
          (await getRiskInfo({
            companyName: this.companyInfo.companyName,
          })) || {};

        this.riskList = riskList;

        //将接口返回的风险列表数组进行反转
        this.riskList.forEach((item) => item.list?.reverse());
      } finally {
        Toast.closeLoading();
      }
    },

    /**
     * 获取总公司信息数据
     */
    async getParentCompanyInfo() {
      try {
        Toast.startLoading();

        //获取总公司数据
        this.parentCompanyObj =
          (await getParentCompany({
            companyName: this.companyInfo.companyName,
            pageNum: 1,
          })) || {};
      } finally {
        Toast.closeLoading();
      }
    },

    /**
     * 获取二级导航数据
     * @param {*} id 导航栏id，找到navList中与之相同的id，拿取到该对象中的children数据，过滤返回不会为空
     */
    getNavChildren(id) {
      return this.navList.filter((item) => item.id == id)[0].children;
    },

    /**
     * 一级导航切换
     * @param {*} id 点击的导航id
     * @param name 导航名字
     * @param {*} type 点击的导航类型
     * @param index 导航index
     * @param {*} navRequestStatus 导航请求状态
     */
    handleParentList({ id, name, type, index = 0, navRequestStatus } = {}) {
      sessionStorage.setItem(this.companyInfo.id, JSON.stringify({ id, name, type, index, navRequestStatus }));
      //赋值
      this.id = id;
      this.type = type;

      this.setRiskTitle(name);

      //导航切换重新加载数据
      this.loadData(navRequestStatus);

      //将当前点击的一级导航栏目设置为选中，反之不选中
      this.navList.forEach((item) => {
        item.isActive = item.id == id;
      });

      //设置二级导航第一个栏目选中展示
      if (type !== "PresentContent") {
        this.setTwoStageNavActive(id);
      }
    },

    /**
     * 二级导航切换
     * @param {*} id 点击的导航id
     * @param {*} type 点击的导航类型
     * @param {*} index 下标
     * @param {*} navRequestStatus 导航请求状态
     */
    handleChildrenList({ id, name, type, index, navRequestStatus } = {}) {
      sessionStorage.setItem(
        this.companyInfo.id,
        JSON.stringify({
          id,
          name,
          type,
          index,
          navRequestStatus: this.id === 3 ? RISK_DETAILS_REQUEST : navRequestStatus,
        }),
      );
      //赋值
      this.type = type;

      this.setRiskTitle(name);

      //导航切换重新加载数据
      this.loadData(navRequestStatus);

      //设置二级导航栏目选中展示
      this.setTwoStageNavActive(id, index);

      //设置二级导航栏滑动，让点击的栏目滚动到中间区域
      this.$nextTick(() => {
        elementSlide(this.$refs.navListChildren, `.${type}`);
      });

      //让列表容器滚动条回到顶部
      $(".enterprise-details-container").animate({ scrollTop: 0 }, 0);
    },

    /**
     * 设置二级导航选中效果
     * @param {*} id 点击的导航id
     * @param {*} index 下标 默认是第一个
     */
    setTwoStageNavActive(id, index = 0) {
      this.getNavChildren(id).forEach((o, i) => {
        o.isActive = i == index;
      });
    },

    /**
     * 重新加载数据
     * @param {*} navRequestStatus 导航请求状态
     */
    loadData(navRequestStatus) {
      switch (navRequestStatus) {
        case SAME_PARAMETERS_REQUEST:
          //处理股东、电信许可、资质证书、投资情况
          this.vantListGather.list = [];
          this.vantListGather.pageNum = 1;
          this.vantListGather.loading = false;
          this.vantListGather.finished = false;

          //请求数据
          this.getData(this.type);
          break;
        case RISK_DETAILS_REQUEST:
          //处理风险信息
          this.getRiskInfo();
          break;
        case PARENT_COMPANY_REQUEST:
          //处理总公司信息
          this.getParentCompanyInfo();
          break;
      }
    },

    /**
     * 加载下一页，滚动条与底部距离小于 offset 时触发
     * @param {*} pageNum 页码
     */
    onLoad(pageNum) {
      //设置页码
      this.vantListGather.pageNum = pageNum;

      //请求数据
      this.getData(this.type);
    },

    /**
     * 设置风险标题
     * @param {*} title 标题
     */
    setRiskTitle(title) {
      if (this.id === RISK_ID) {
        this.riskTitle = title;
      }
    },

    /**
     * 设置企业详情信息高度
     */
    setEnterpriseDetailsConHeight() {
      const { enterpriseInfo, headerContainer, navList, navListChildren, enterpriseDetailsContainer } = this.$refs || {};

      $(enterpriseDetailsContainer?.$el || ".enterprise-details-container").height(
        $("body").outerHeight(true) -
          $(headerContainer?.$el || ".header-container").outerHeight(true) -
          $(navList).outerHeight(true) -
          $(enterpriseInfo).outerHeight(true) -
          $(navListChildren).outerHeight(true) -
          20,
      );
    },

    /**
     * 进入商业角色页面
     * @param {*} humanName 人名
     */
    handleBusinessRole(humanName) {
      jumpPage(this, "BusinessRole", {
        companyName: this.companyInfo.companyName,
        humanName,
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import url("~@/assets/styles/enterpriseInfoQuery/index.less");
.bg-scrollFake {
  background-color: #fff;
  padding: 20px 0 10px;
  .scrollFake {
    margin: 0 auto;
    width: 87px;
    height: 8px;
    border-radius: 10px;
    position: relative;
    background: rgba(232, 232, 232, 1);
    border: 1px solid #ccc;
    .scrollBar {
      position: absolute;
      height: 100%;
      width: 40px;
      border-radius: 5px;
      left: 0;
      background: rgba(26, 133, 255, 1);
    }
  }
}
</style>
